import requests
import re
import os
import zipfile


url = input('请输入视频网址：')

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
}
response = requests.get(url=url,headers=headers)
#print(response.text)
                                            #取第一行，       替换字符
m3u8_url = re.findall('"backupUrl(.*?)"]',response.text)[0].replace('\\":[\\"','').replace('\\','')
title = re.findall('<title >(.*?)- AcFun弹幕视频网 - 认真你就输啦 \(\?\ω\?\)ノ- \( ゜- ゜\)つロ</title>',response.text)[0]
#print(m3u8_url)

#os自动创建文件夹
filename = f'{title}\\'
if not os.path.exists(filename):
    os.mkdir(filename)


m3u8_data = requests.get(url=m3u8_url,headers=headers).text
m3u8_data = re.sub('#EXTM3U','',m3u8_data)
m3u8_data = re.sub('#EXT-X-VERSION:\d','',m3u8_data)
m3u8_data = re.sub('#EXT-X-TARGETDURATION:\d','',m3u8_data)
m3u8_data = re.sub('#EXT-X-MEDIA-SEQUENCE:\d','',m3u8_data)
m3u8_data = re.sub('#EXTINF:\d\.\d+,','',m3u8_data)
m3u8_data = re.sub('#EXT-X-ENDLIST','',m3u8_data).split()
#print(m3u8_data)
for index in m3u8_data:
    ts_url = 'https://ali-safety-video.acfun.cn/mediacloud/acfun/acfun_video/hls/' + index
    ts_name = ts_url.split('.')[3]
                                                         #二进制
    ts_content = requests.get(url=ts_url,headers=headers).content

    with open(filename + ts_name + '.ts',mode='wb') as f:
        f.write(ts_content)
        print(ts_name)

print('视频片段下载完成')
print('开始合并......')

files = os.listdir(filename)
print(files)
with zipfile.ZipFile(filename + title + '.mp4',mode='w') as f:
    for i in files:
        file = filename + i
        f.write(file)
        os.remove(file)
print('爬取完成')



